﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommonTagTime.PagerControl;
using CommonTagTime.Business;
using CommonTagTime.ModelObject;
using CommonTagTime;
using System.Collections;
public partial class admin_DistributorList : SitePage
{
    #region ViewState
    private string linkDetail = "CategoryDetail.aspx?id={0}&act=edit";
    public int count = 0;
    public string paraURL
    {
        get
        {
            object o = ViewState["paraURL"];
            if (o != null) return (string)o;
            return string.Empty;
        }
        set { ViewState["paraURL"] = value; }

    }
    public int F_PageIndex
    {
        get
        {
            object o = ViewState["F_PageIndex"];
            if (o != null) return (int)o;
            return 0;                        //a default

        }
        set { ViewState["F_PageIndex"] = value; }

    }
    public int F_PageSize
    {
        get
        {
            object o = ViewState["F_PageSize"];
            if (o != null) return (int)o;
            return 0;                        //a default

        }
        set { ViewState["F_PageSize"] = value; }

    }
    public string F_SortField
    {

        get
        {
            object o = ViewState["F_SortField"];
            if (o != null) return (string)o;
            return string.Empty;
        }

        set { ViewState["F_SortField"] = value; }

    }
    public string F_SortExpression
    {

        get
        {
            object o = ViewState["F_SortExpression"];
            if (o != null) return (string)o;
            return string.Empty;
        }

        set { ViewState["F_SortExpression"] = value; }

    }
    #endregion

    #region Init,Loads
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!Page.IsPostBack)
        {
            LoadCountryData();
            LoadStateByCountry();
            clsBindControl.BindBooleanCombobox(F_ddlIsActive);
            GetParamater();
            LoadData();
        }
        //  Response.Write("Application:" + this.ApplicationName);
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
       
    }
    #endregion

    #region Events
    protected void Pager2_PageIndexChanging(object obj, PageIndexChangeEventArgs e)
    {
        this.F_PageIndex = e.PageIndex;
        LoadData();
    }
    protected void Pager2_PageSizeChanging(object obj, PageSizeChangeEventArgs e)
    {
        this.F_PageIndex = 1;
        Pager2.PageSize = Pager1.PageSize = e.PageSize;
        LoadData();
    }
    protected void rptData_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Distributor cate = (Distributor)e.Item.DataItem;
            if (cate == null)
                return;
            hidDistributorID.Value += cate.DistributorID.ToString() + ";";

            //image button IsActive
            ImageButton imgButton = (ImageButton)e.Item.FindControl("imbActive");
            imgButton.CommandArgument = cate.DistributorID.ToString();
            if (cate.IsActive == true)
            {
                imgButton.ImageUrl = clsString.ACTIVE_IMAGE_URL;
                imgButton.ToolTip = Resources.Resource.TIP_DEACTIVE;
                imgButton.CommandName = "DeActive";
            }
            else
            {
                imgButton.ImageUrl = clsString.DEACTIVE_IMAGE_URL;
                imgButton.ToolTip = Resources.Resource.TIP_ACTIVE;
                imgButton.CommandName = "Active";
            }

            imgButton = (ImageButton)e.Item.FindControl("imbDelete");
            imgButton.ToolTip = Resources.Resource.TIP_DELETE;
            imgButton.Attributes.Add("onclick", "return confirm('" + Resources.Resource.MSG_CONFIRM_DELETE + "');");
            imgButton.CommandArgument = cate.DistributorID.ToString();
            imgButton.ImageUrl = clsString.DELETE_IMAGE_URL;


        }

    }
    protected void rptData_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "SortOrder")
        {
            SortList(e.CommandArgument.ToString());

        }
        else
        {
            int id = clsConvert.Int(e.CommandArgument.ToString());
            switch (e.CommandName)
            {


                case "Active":
                    {
                        Active(id);
                        break;
                    }
                case "DeActive":
                    {
                        DeActive(id);
                        break;
                    }

                case "Delete":
                    {
                        Delete(id);
                        break;
                    }
            }
        }
    }

    private void SortList(string F_SortField)
    {
        if (this.F_SortField == F_SortField)
        {
            if (this.F_SortExpression == "ASC")
                this.F_SortExpression = "DESC";
            else this.F_SortExpression = "ASC";
        }
        else
        {
            this.F_SortField = F_SortField;
            this.F_SortExpression = "ASC";
        }
        LoadData();
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        this.F_PageIndex = 1;
        LoadData();
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        busDistributor objBus = new busDistributor();
        string[] arr = hidDistributorIDSelect.Value.Split(';');
        for (int i = 0; i < arr.Length; i++)
        {
            if (arr[i].ToString() != string.Empty)
                objBus.Delete(clsConvert.Int(arr[i].ToString()));
        }
        LoadData();

    }


    #endregion

    #region Methods
    private void LoadCountryData()
    {
        Category objCondition = new Category();
        objCondition.OrderBy = busCategory.SORTORDER;
        objCondition.OrderDirection = "ASC";
        objCondition.Condition = " ParentId is null and Type=" + (byte)enmCategoryType.Area;
        objCondition.CurrentPage = 1;
        objCondition.PageSize = int.MaxValue;
        busCategory objBus = new busCategory();
        CategoryCollection lstLevel1 = objBus.List(objCondition);//only return one object
        bool addEmpty = true;
        if (lstLevel1 != null && lstLevel1.Count > 0)
        {
            addEmpty = false;
            foreach (Category objData in lstLevel1)
            {
                AddNode(objData, false);
            }

        }
        if (addEmpty)
            F_ddlCountry.Items.Insert(0, new ListItem("- - -", string.Empty));
    }
    private void AddNode(Category objData, bool isCountry)
    {
        string prefix = string.Empty;
        for (int i = 2; i <= objData.Level; i++)
        {
            prefix += " - - ";
        }
        if (!isCountry)
            F_ddlCountry.Items.Add(new ListItem(prefix + objData.Name, objData.CategoryID.ToString()));
        else F_ddlCountry.Items.Add(new ListItem(prefix + objData.Name, objData.CategoryID.ToString() + "*"));
        CategoryCollection lstChild = GetChild(objData);
        if (lstChild != null && lstChild.Count > 0)
        {
            foreach (Category objChild in lstChild)
            {
                AddNode(objChild, false);
            }
        }
        else
        { //load Country
            lstChild = GetCountryForCate(objData);
            if (lstChild != null && lstChild.Count > 0)
            {
                foreach (Category objChild in lstChild)
                {
                    AddNode(objChild, true);
                }
            }
        }
    }
    public CategoryCollection GetCountryForCate(Category objParent)
    {
        CategoryCollection lstResult = new CategoryCollection();
        busCountryAreaCategory objBus = new busCountryAreaCategory();
        CountryAreaCategoryCollection lstAreaCate = objBus.GetByCategoryId(objParent.CategoryID);
        if (lstAreaCate != null && lstAreaCate.Count > 0)
        {
            busCountry objBusCountry = new busCountry();
            foreach (CountryAreaCategory objCateArea in lstAreaCate)
            {
                Country objCountry = objBusCountry.GetById(objCateArea.CountryID);
                if (objCountry != null)
                {
                    Category objCate = new Category();
                    objCate.CategoryID = objCountry.CountryID;
                    objCate.Name = objCountry.CountryName;
                    objCate.Level = (byte)(objParent.Level + 1);
                    lstResult.Add(objCate);
                }
            }
        }
        return lstResult;
    }
    private CategoryCollection GetChild(Category objData)
    {
        Category objCondition = new Category();
        objCondition.OrderBy = busCategory.SORTORDER;
        objCondition.OrderDirection = "ASC";
        objCondition.Condition = " ParentId=" + objData.CategoryID + " and Type=" + (byte)enmCategoryType.Area;
        objCondition.CurrentPage = 1;
        objCondition.PageSize = int.MaxValue;
        busCategory objBus = new busCategory();
        CategoryCollection lstResult = objBus.List(objCondition);
        return lstResult;
    }
    private CategoryCollection GetChildById(int CategoryId)
    {
        Category objCondition = new Category();
        objCondition.OrderBy = busCategory.SORTORDER;
        objCondition.OrderDirection = "ASC";
        objCondition.Condition = " ParentId=" + CategoryId + " and Type=" + (byte)enmCategoryType.Area;
        objCondition.CurrentPage = 1;
        objCondition.PageSize = int.MaxValue;
        busCategory objBus = new busCategory();
        CategoryCollection lstResult = objBus.List(objCondition);
        return lstResult;
    }
    private void Active(int id)
    {
        busDistributor objBus = new busDistributor();
        if (objBus.Active(id))
            LoadData();
    }
    private void DeActive(int id)
    {
        busDistributor objBus = new busDistributor();
        if (objBus.DeActive(id))
            LoadData();
    }
    private void Delete(int id)
    {
        busDistributor objBus = new busDistributor();
        if (objBus.Delete(id))
            LoadData();
    }
    public string GetCountryCondition()
    {
        string value = F_ddlCountry.SelectedValue;
        if (value == string.Empty)
            return string.Empty;
        if (value.Contains("*"))
        {

            busCountry objBusCountry = new busCountry();
            value = value.Substring(0, value.Length - 1);
            Country objCountry = objBusCountry.GetById(clsConvert.Int(value));
            if (objCountry != null)
            {
                return " and s.CountryCode='" + objCountry.CountryCode + "'";
            }

        }
        //get all contry code for this Area
        string countryCode = GetAllCountryCodeForCate(clsConvert.Int(value));
        //AF','AS','FQ','BG','BB','BS','TX','AQ','AR','AA','US','AG','AO','AV','AY','AC','AM','AT','AL','AN','AU','BO','BE','BH','
        if (countryCode != string.Empty)
        {
            countryCode = countryCode.Substring(0, countryCode.Length - 2);
            countryCode = "'" + countryCode;
            return " and s.CountryCode in(" + countryCode + ")";
        }
        return string.Empty;
    }

    private string GetAllCountryCodeForCate(int cate)
    {
        string result = string.Empty;
        CategoryCollection lstCateChild = GetChildById(cate);
        if (lstCateChild != null && lstCateChild.Count > 0)
        {
            foreach (Category objCate in lstCateChild)
            {
                result += GetAllCountryCodeForCate(objCate.CategoryID);
            }
        }
        else
        {
            CategoryCollection lstResult = new CategoryCollection();
            busCountryAreaCategory objBus = new busCountryAreaCategory();
            CountryAreaCategoryCollection lstAreaCate = objBus.GetByCategoryId(cate);
            if (lstAreaCate != null && lstAreaCate.Count > 0)
            {
                busCountry objBusCountry = new busCountry();
                foreach (CountryAreaCategory objCateArea in lstAreaCate)
                {
                    Country objCountry = objBusCountry.GetById(objCateArea.CountryID);
                    if (objCountry != null)
                    {
                        result += objCountry.CountryCode + "','";
                    }
                }

            }
        }
        return result;
    }
    private void LoadData()
    {
        paraURL = GetPageParams(FilterFieldType.All);
        hidDistributorID.Value = string.Empty;
        //get Condition
        Distributor objDistributor = new Distributor();
        // objCate.Name = txtCategoryName.Text;
        objDistributor.CurrentPage = this.F_PageIndex;
        objDistributor.OrderBy = this.F_SortField;
        objDistributor.OrderDirection = this.F_SortExpression;
        objDistributor.PageSize = Pager1.PageSize;
        string condition = " 1=1 ";
        if (F_ddlCountry.SelectedValue != string.Empty)
        {
            condition += GetCountryCondition();// " and s.CountryCode='" + F_ddlCountry.SelectedValue + "'";
        }
        if (F_ddlState.SelectedValue != string.Empty)
            condition += " and s.StateCode='" + F_ddlState.SelectedValue + "'";
        if (F_txtProvince.Text != string.Empty)
            condition += " and s.Province like N'%" + F_txtProvince.Text + "%'";
        if (F_txtCity.Text != string.Empty)
            condition += " and s.City like N'%" + F_txtCity.Text + "%'";

        if (F_txtCompanyName.Text != string.Empty)
            condition += " and s.CompanyName like N'%" + F_txtCompanyName.Text + "%'";
        if (F_txtContactName.Text != string.Empty)
            condition += " and s.ContactName like N'%" + F_txtContactName.Text + "%'";

        if (F_txtEmail.Text != string.Empty)
            condition += " and s.Email like N'%" + F_txtEmail.Text + "%'";
        if (F_ddlIsActive.SelectedValue != string.Empty)
            condition += " and s.IsActive=" + F_ddlIsActive.SelectedValue;
        objDistributor.Condition = condition;
        busDistributor _busDistributor = new busDistributor();
        DistributorCollection lstResult = _busDistributor.List(objDistributor);
        if (lstResult != null && lstResult.Count > 0)
        {
            count = lstResult.Count;
            rptData.DataSource = lstResult;
            divGrid.Visible = true;
            divEmplty.Visible = false;
        }
        else
        {
            rptData.DataSource = null;
            divGrid.Visible = false;
            divEmplty.Visible = true;
            divEmplty.InnerHtml = Resources.Resource.MSG_EMPTY;
        }
        rptData.DataBind();
        Pager1.SetPaging(this.F_PageIndex, count, objDistributor.TotalRecords);
        Pager2.SetPaging(this.F_PageIndex, count, objDistributor.TotalRecords);
    }
    private void GetParamater()
    {
        F_ddlCountry.Text = clsQueryString.GetString("F_ddlCountry");
        LoadStateByCountry();
        F_ddlState.Text = clsQueryString.GetString("F_ddlState");
        F_txtCompanyName.Text = clsQueryString.GetString("F_txtCompanyName");
        F_txtContactName.Text = clsQueryString.GetString("F_txtContactName");
        F_txtEmail.Text = clsQueryString.GetString("F_txtEmail");
        F_txtProvince.Text = clsQueryString.GetString("F_txtProvince");
        F_txtCity.Text = clsQueryString.GetString("F_txtCity");       
        this.F_SortField = clsQueryString.GetString("F_SortField");
        if (this.F_SortField == string.Empty)
            this.F_SortField = busDistributor.COMPANYNAME;
        this.F_SortExpression = clsQueryString.GetString("F_SortExpression");
        if (this.F_SortExpression == string.Empty)
            this.F_SortExpression = "ASC";
        F_PageIndex = clsQueryString.GetInt("F_PageIndex");
        F_PageSize = clsQueryString.GetInt("F_PageSize");
        if (F_PageSize < 1)
            F_PageSize = clsConfigData.DEFAULT_ADMIN_PAGE_SIZE;
        if (F_PageIndex < 1)
            F_PageIndex = 1;
        this.Pager2.PageSize = this.Pager1.PageSize = F_PageSize;
        F_ddlIsActive.SelectedValue = clsQueryString.GetString("F_ddlIsActive");    

    }
    private string GetCondition(Category objCate)
    {
        string result = "1=1";
        if (objCate.Name != string.Empty)
            result += " and c.Name like N'%" + objCate.Name + "%'";
        return result;
    }
    #endregion

    protected void F_ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadStateByCountry();
    }
    private void LoadStateByCountry()
    {
        F_ddlState.Items.Clear();
         string value = F_ddlCountry.SelectedValue;
        if (value != string.Empty)
        {
            if (value.Contains("*"))
            {        
                value = value.Substring(0, value.Length - 1);
                busState objBus = new busState();
                StateCollection lstState = objBus.GetByCountryId(clsConvert.Int(value));
                F_ddlState.DataSource = lstState;
                F_ddlState.DataTextField = busState.STATENAME;
                F_ddlState.DataValueField = busState.STATECODE;
                F_ddlState.DataBind();
            }
        }
        F_ddlState.Items.Insert(0, new ListItem("- - -", ""));
    }
}